﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CNotebook
{
    public class CardDocumentManager:ConnectionManager
    {
        public DataTable GetCardDocument()
        {
            SqlCommand oCommand = new SqlCommand();
            DataSet ds = new DataSet();

            oCommand.Connection = this.Connection;
            oCommand.CommandText = "SELECT * FROM CARD_DOCUMENT";

            SqlDataAdapter oAdapter = new SqlDataAdapter();
            oAdapter.SelectCommand = oCommand;
            oAdapter.Fill(ds);

            return ds.Tables[0];
        }

        public DataTable GetCardDocumentForGrid()
        {
            SqlCommand oCommand = new SqlCommand();
            DataSet ds = new DataSet();

            oCommand.Connection = this.Connection;
            oCommand.CommandText = "SELECT Code OldCode, * FROM CARD_DOCUMENT";

            SqlDataAdapter oAdapter = new SqlDataAdapter();
            oAdapter.SelectCommand = oCommand;
            oAdapter.Fill(ds);

            return ds.Tables[0];
        }

        public SqlDataAdapter UpdateCardDocument(DataTable dt)
        {
            SqlCommand oCommand = new SqlCommand();
            try
            {
                foreach (DataRow oRow in dt.Rows)
                {
                    if (oRow.RowState == DataRowState.Added)
                    {
                        oCommand = new SqlCommand();
                        oCommand.Connection = this.Connection;
                        oCommand.CommandText = "INSERT INTO CARD_DOCUMENT (Code, Dscription) VALUES (@Code, @Dscription)";

                        oCommand.Parameters.Add(new SqlParameter("@Code", oRow["Code"].ToString()));
                        oCommand.Parameters.Add(new SqlParameter("@Dscription", oRow["Dscription"].ToString()));

                        oCommand.ExecuteNonQuery();
                    }

                    if (oRow.RowState == DataRowState.Modified)
                    {
                       oCommand = new SqlCommand();
                        oCommand.Connection = this.Connection;
                        oCommand.CommandText = "UPDATE CARD_DOCUMENT SET Code=@Code, Dscription=@Dscription WHERE Code=@OldCode";

                        oCommand.Parameters.Add(new SqlParameter("@OldCode", oRow["OldCode"].ToString()));
                        oCommand.Parameters.Add(new SqlParameter("@Code", oRow["Code"].ToString()));
                        oCommand.Parameters.Add(new SqlParameter("@Dscription", oRow["Dscription"].ToString()));

                        oCommand.ExecuteNonQuery();
                    }
                }
                throw null;
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }

    }
}
